﻿using System.Security.Claims;
using System.Web;
using System.Web.Mvc;
using Inovout.Component;
using Inovout.Security;
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
using MvcSiteMapProvider;
using Newtonsoft.Json;
using System.Net.Http;
using System;
using System.Collections.Generic;
using System.Linq;


namespace Inovout.Web.Mvc.Security
{
    [AllowAnonymous]
    public class OAuthAccountController : BaseController
    {
        private ICredentialValidator credentialValidator;

        public OAuthAccountController()
        {

        }

        public OAuthAccountController(ICredentialValidator credentialValidator)
        {
            this.credentialValidator = credentialValidator;
        }

        public ActionResult External(string id, string provider, string returnUrl)
        {
            provider = provider ?? id;
            var properties = new AuthenticationProperties()
            {
                RedirectUri = Url.Action("ExtensionalCallback", new { ReturnUrl = returnUrl })
            };
            AuthenticationManager.Challenge(properties, provider);
            return new HttpUnauthorizedResult();

        }

        private IAuthenticationManager AuthenticationManager
        {
            get
            {
                return HttpContext.GetOwinContext().Authentication;
            }
        }

        public ActionResult ExtensionalCallback(string returnUrl)
        {
            var externalLoginInfo = AuthenticationManager.GetExternalLoginInfo();
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
            if (externalLoginInfo != null)
            {
                var identity = new ClaimsIdentity(externalLoginInfo.ExternalIdentity.Claims, DefaultAuthenticationTypes.ApplicationCookie
                        , externalLoginInfo.ExternalIdentity.NameClaimType, externalLoginInfo.ExternalIdentity.RoleClaimType);

                AuthenticationManager.SignIn(
                    new AuthenticationProperties { IsPersistent = false }, identity);
                if (ComponentRegistry.IsRegistered<IMembershipProvider>())
                {
                    GetService<IMembershipProvider>().OnSignIn(identity);
                }
            }

            return RedirectToReturnUrl(returnUrl);

        }
        private IExtentenalCredential ConvvertByWeibo(object obj)
        {
            IExtentenalCredential credential = ComponentRegistry.Resolve<IExtentenalCredential>();

            return null;
        }
        protected ActionResult SignIn(ICredential credential, string returnUrl, bool isPersistent = false)
        {
            string provider = credential.GetType().Name.Substring(0, credential.GetType().Name.Length - "Credential".Length);
            ViewBag.ReturnUrl = returnUrl;
            if (!ModelState.IsValid)
            {
                return View(provider, credential);
            }

            IMembershipUser membershipUser = credentialValidator.Validate(credential);
            if (membershipUser == null)
            {
                ModelState.AddModelError("Code", "验证码错误");
                return View(provider, credential);
            }
            var authentication = HttpContext.GetOwinContext().Authentication;
            authentication.SignIn(
              new AuthenticationProperties { IsPersistent = isPersistent },
              new ClaimsIdentity(new[] { new Claim(ClaimsIdentity.DefaultNameClaimType, membershipUser.Identity.ToString()) }, provider)
          );
            return View();
            //return new HttpUnauthorizedResult();
        }
        public ActionResult SignOut(string returnUrl)
        {
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);

            if (!string.IsNullOrEmpty(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return View();
                //Redirect("~/");
            }
        }

        /// <summary>
        /// 同步MVC.SITE中的内容
        /// </summary>
        public  void SyncPrivilege()
        {
            ResourceProvider.SyncResource();
        }

    }
}
